package rush.rushcampus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import rush.rushcampus.common.BaseContext;
import rush.rushcampus.dto.IdlePageDto;
import rush.rushcampus.dto.IdlePublishDto;
import rush.rushcampus.entity.Idle;
import rush.rushcampus.entity.IdleTag;
import rush.rushcampus.entity.User;
import rush.rushcampus.mapper.ArticleMapper;
import rush.rushcampus.mapper.IdleMapper;
import rush.rushcampus.mapper.IdleTagMapper;
import rush.rushcampus.service.IIdleService;
import rush.rushcampus.vo.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class IdleServiceImpl extends ServiceImpl<IdleMapper, Idle> implements IIdleService {
    @Autowired
    private CommentServiceImpl commmentService;
    @Autowired
    private IdleMapper idleMapper;
    @Autowired
    private IdleTagMapper idleTagMapper;
    @Autowired
    private CommentServiceImpl commentService;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UserServiceImpl userService;
    private static final Pattern PATTERN = Pattern.compile("\\d+");
    @Override
    public void addIdle(IdlePublishDto idlePublishDto) {
        Idle idle = new Idle();
        BeanUtils.copyProperties(idlePublishDto,idle);
        idle.setAuthorId(BaseContext.getCurrenId());
        idle.setStatus(0);
        idle.setIsChoice(0);
        idle.setViewCount(0L);
        idle.setLikeCount(0L);
        idle.setCommentCount(0L);
        idle.setStarCount(0L);
        idle.setCreateTime(LocalDateTime.now());
        this.save(idle);
    }



    @Override
    public List<IdleVo> listIdleVo(IdlePageDto idlePageDto) {
        Integer currentPage = idlePageDto.getPage();
        Integer pageSize = idlePageDto.getSize();

        List<IdleVo> idleVoList = new ArrayList<>();
        Page<Idle> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Idle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", idlePageDto.getStatus());
        queryWrapper.eq(idlePageDto.getType()!= null , "type", idlePageDto.getType());
        // 检查 tagId 是否非 null，如果非 null，则在查询条件中加入该条件
        queryWrapper.apply(idlePageDto.getTagId() != null, "FIND_IN_SET({0}, tag_ids)", idlePageDto.getTagId());
        if (idlePageDto.getStar() != null && !idlePageDto.getStar().trim().isEmpty()) {
            List<Long> starList = Arrays.stream(idlePageDto.getStar().split(","))
                    .filter(s -> !s.trim().isEmpty()) // 过滤掉空字符串
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            queryWrapper.in("id", starList);
        } else {
            // 如果 getStar() 为空或者只有空白字符，则不添加这个查询条件
        }
        // 执行分页查询
        List<Idle> idleList = idleMapper.selectPage(page, queryWrapper).getRecords();

        // 遍历查询到的记录，处理标签信息
        for (Idle idle1 : idleList) {
            String idle1Tag = idle1.getTagIds();
            List<IdleTag> tagList = new ArrayList<>();

            Matcher matcher = PATTERN.matcher(idle1Tag);

            // 获取标签列表
            while (matcher.find()) {
                String tagId = matcher.group();
                IdleTag idleTag = idleTagMapper.selectById(tagId);
                tagList.add(idleTag);
            }

            // 创建 VO 对象并复制属性
            IdleVo idleVo = new IdleVo();
            BeanUtils.copyProperties(idle1, idleVo);
            idleVo.setTagsList(tagList);
            idleVoList.add(idleVo);
        }

        return idleVoList;

    }

    @Override
    public void removeIdle(Long id, Integer commentType) {
        //1.删除该闲置下的评论
        commentService.deleteCommentAndChildren(id, commentType);
        //2.删除闲置
        idleMapper.deleteById(id);
    }

    @Override
    public IdleInfoVo getIdleById(Long id) {
        QueryWrapper<Idle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        queryWrapper.eq("id", id);
        Idle idle  = idleMapper.selectOne(queryWrapper);
        articleMapper.incrementIdleById(id);
        User user = userService.getById(idle.getAuthorId());
        UserPartInfoVo userPartInfoVo = new UserPartInfoVo();
        userPartInfoVo.setCreateUserName(user.getNickname());
        userPartInfoVo.setCreateUserAvatar(user.getAvatar());
        userPartInfoVo.setCreateUserSex(user.getGender());
        IdleInfoVo idleInfoVo = new IdleInfoVo();
        idleInfoVo.setUserPartInfoVo(userPartInfoVo);
        idleInfoVo.setCreateTime(idle.getCreateTime());
        idleInfoVo.setView(idle.getViewCount());
        idleInfoVo.setLoveNumber(idle.getLikeCount());
        idleInfoVo.setStarNumber(idle.getStarCount());
        idleInfoVo.setStarNumber(idle.getStarCount());
        idleInfoVo.setCommentNumber(commentService.countComment(id, 2));
        idleInfoVo.setContent(idle.getContent());
        idleInfoVo.setImgList(idle.getImgList());
        //查询评论，赋值
//        List<ArticleCommentVo> articleCommentVoList = commentService.listComment(id, 0, 1, 10);
        List<ArticleCommentVo> articleCommentVoList = commentService.listArticleComment(id , 2);
        idleInfoVo.setArticleCommentVoList(articleCommentVoList);
        return idleInfoVo;
    }
}
